package com.weijian.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.weijian.common.MessageWrapper;
import com.weijian.dal.dataobject.BaseConversation;
import com.weijian.service.MpConversationService;
import com.weijian.service.ChatService;
import com.weijian.dal.vo.ConversationVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {

    private final MpConversationService conversationService;

    @Override
    public ConversationVO create() {
        String conversationId = UUID.randomUUID().toString();
        String title = "New Chat";
        conversationService.save(BaseConversation.builder()
                .conversationId(conversationId)
                .title(title)
                .build());
        return ConversationVO.builder().conversationId(conversationId)
                .title(title)
                .build();
    }

    @Override
    public void edit(String conversationId, String title) {
        if (!StringUtils.hasText(title)) {
            return;
        }
        conversationService.update(BaseConversation.builder().title(title).build(),
                new LambdaQueryWrapper<BaseConversation>().eq(BaseConversation::getConversationId, conversationId));
    }

    @Override
    public List<ConversationVO> list() {
        return conversationService.list(new LambdaQueryWrapper<BaseConversation>().orderByAsc(BaseConversation::getCreateTime))
                .stream().map(v -> ConversationVO.builder()
                        .conversationId(v.getConversationId())
                        .title(v.getTitle())
                        .build()).toList();
    }

    @Override
    public void delete(String conversationId) {
        conversationService.remove(
                new LambdaQueryWrapper<BaseConversation>().eq(BaseConversation::getConversationId, conversationId));
    }

    @Override
    public ConversationVO get(String conversationId) {
        return conversationService.getOneOpt(
                        new LambdaQueryWrapper<BaseConversation>().eq(BaseConversation::getConversationId, conversationId))
                .map(v -> ConversationVO.builder().conversationId(v.getConversationId())
                        .title(v.getTitle())
                        .messages(MessageWrapper.fromConversationStr(v.getContent()))
                        .build()
                ).orElseThrow(() -> new RuntimeException("can not find conversation with id: %s ".formatted(conversationId)));

    }

}
